package com.spider.moudle.pool;

import com.spider.moudle.task.TaskQuery;
import com.spider.moudle.util.PropertiesUtil;

import java.util.LinkedList;

/**
 * Created by Linbo Hu on 2017/12/7.
 * 查询用户主页的pool
 */
public class TaskQueryPool {

    private static TaskQueryPool instance = new TaskQueryPool();

    private final LinkedList<TaskQuery> pool = new LinkedList<>();


    public TaskQueryPool() {
        int num = Integer.parseInt(PropertiesUtil.getVal("task.query.init.num"));
        for(int i = 0; i < num; i++) {
            TaskQuery taskQuery = new TaskQuery();
            synchronized(pool) {
                pool.add(taskQuery);
                pool.notifyAll();
            }
        }
    }

    public static TaskQueryPool getInstance() {
        return instance;
    }


    /**
     * 获取一个连接器
     * @return
     * @throws InterruptedException
     */
    public TaskQuery fetchTaskQuery() throws InterruptedException {
        synchronized(pool) {
            while(pool.isEmpty()) {
                pool.wait();
            }
            return pool.removeFirst();

        }
    }



    /**
     * 释放一个连接器
     * @param connection
     */
    public void releaseTaskQuery(TaskQuery connection) {
        if(connection != null) {
            synchronized (pool) {
                pool.addLast(connection);
                pool.notifyAll();
            }
        }
    }
}
